package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.blankj.utilcode.util.SizeUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.CommVLayoutAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.BorrowingInfo;
import com.chexiehui.jc.mvp.home.LoanServicesListCovenant;
import com.chexiehui.jc.mvp.home.LoanServicesListPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * 借款服务
 */
public class LoanServicesListActivity extends BaseMvpActivity<LoanServicesListPresenter> implements LoanServicesListCovenant.View {
    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private DelegateAdapter listAdapter;
    private CommVLayoutAdapter<BorrowingInfo> loanAdapter;
    private BasePage<BorrowingInfo> page;

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("借款服务");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_loan_services_list;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > loanAdapter.getData().size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });

        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });

        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(mContext);
        mRecycler.setLayoutManager(virtualLayoutManager);
        ((SimpleItemAnimator) mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mRecycler.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 20);
        listAdapter = new DelegateAdapter(virtualLayoutManager, false);
        mRecycler.setAdapter(listAdapter);

        int dp_10 = SizeUtils.dp2px(10);
        LinearLayoutHelper helper = new LinearLayoutHelper(dp_10);
        helper.setPadding(dp_10, dp_10, dp_10, dp_10);
        helper.setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent));
        loanAdapter = new CommVLayoutAdapter<BorrowingInfo>(mContext, new ArrayList<>(),
                R.layout.item_loan_services, helper) {
            @Override
            public void convert(ViewHolder holder, int position, BorrowingInfo item) {
                holder.setText(R.id.tv_item_title, item.getName());
                holder.setText(R.id.tv_item_quota, item.getLinesModule());
                holder.setText(R.id.tv_item_interest, item.getDayInterest() + "%");
            }
        };
        loanAdapter.setItemClickListener((view, position, item) ->
                startActivity(MortgageApplyActivity.class, new BundleBuilder()
                .putString("borrowingId", item.getId()).create()));
        listAdapter.addAdapter(loanAdapter);
        mvpPresenter.getList(1);
    }

    @Override
    protected LoanServicesListPresenter createPresenter() {
        return new LoanServicesListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<BorrowingInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            loanAdapter.getData().clear();
            loanAdapter.getData().addAll(page.getItems());
            loanAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            loanAdapter.getData().addAll(page.getItems());
            loanAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= loanAdapter.getData().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            loanAdapter.getData().clear();
            loanAdapter.getData().addAll(page.getItems());
            loanAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (loanAdapter.getData().size() > 0) {
                    loanAdapter.getData().clear();
                    loanAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (loanAdapter.getData().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }
}
